import os
import uvicorn
from pathlib import Path
from app.core.logger import get_logger
import dotenv
import os

# 获取logger实例
logger = get_logger("run")

# 确保工作目录正确
def start_server():
    # 显式加载.env文件
    backend_dir = os.path.dirname(os.path.abspath(__file__))
    dotenv_path = os.path.join(backend_dir, '.env')
    if os.path.exists(dotenv_path):
        dotenv.load_dotenv(dotenv_path)
        logger.info(f'Loaded environment variables from: {dotenv_path}')
    """启动FastAPI服务器"""
    try:
        # 获取当前文件的目录，即llm_backend目录
        backend_dir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(backend_dir)
        logger.info(f"Changed working directory to: {backend_dir}")
        
        # 启动uvicorn服务器
        logger.info("Starting FastAPI server with uvicorn...")
        uvicorn.run(
            "main:app",
            host="0.0.0.0",
            port=8000,
            reload=True,  # 启用热重载
            log_level="info"
        )
    except Exception as e:
        logger.error(f"Failed to start server: {str(e)}")
        raise

if __name__ == "__main__":
    start_server()